#!/usr/bin/env python
# -*-coding:utf-8-*-

from pysqlite3 import DbHelper
import sys
import requests
import os
import time

reload(sys)
sys.setdefaultencoding("utf-8")


import getqiezivideo


def downloadbyid(id):
    sum, url, picurl = getqiezivideo.detail(id)
    getqiezivideo.g_db.setDownloadFinshed(id, url, sum)
    return url,picurl


def doDownload(videoids):
    range = len(videoids)
    if(range > 100):
        range = 100
    picfile = open('picurl.txt', 'wb')
    videofile = open('videourl.txt', 'wb')
    for i in xrange(range):
        url,picurl = downloadbyid(videoids.pop(0))
        picfile.write(picurl)
        picfile.write("\n")
        videofile.write(url)
        videofile.write("\n")
    picfile.close()
    videofile.close()
    if os.system("aria2c -d videos -c -i videourl.txt") != 0:
        print('down video failed\n')
        sys.exit(0)
    if os.system("aria2c -d pics -c -i picurl.txt") != 0:
        print('down pic failed\n')
        sys.exit(0)

if __name__ == '__main__':
    videoids = getqiezivideo.g_db.getvideoids()
    while (len(videoids) > 0):
        doDownload(videoids)
    print('finished\n')
